const cloud = require('wx-server-sdk')
const { drawPrize } = require('./utils');
const { log, setAward, setLog } = require('./server');
cloud.init({
  env: "yt-active-8gnmft6y371c4f18"
})
const db = cloud.database();
const activeId = "4885635e676b67d10045012b049adf11";
async function info() {
  // 先取出集合记录总数
  // const wxContext = cloud.getWXContext()
  const res = await db.collection('active').doc(activeId).get();
  return {
    ...res
  }
}



async function buy() {
  const errInfo = {
    isAward: false,
    name: "活动已结束",
    _id: null
  }
    const userInfo = await log()
    if (userInfo.hasAward !== "pedding") {
      return {
        success: false,
        errMsg: "您已经抽过奖了~",
        data: null,
      }
    }
    const res = await db.collection('award').skip(0).limit(10).where({
      forActive: activeId
    }).get()
    // 抽奖逻辑
    const info = drawPrize(res.data)
    let infoData = {}
    // 判断中奖日志
    let userAwared = {
      hasAward: "off"
    }
    // 奖品数量够的话进入池子
    if (info.nums <= 0) {
      infoData = {
        ...errInfo,
      }
      userAwared.hasAward = "off"
    } else {
      infoData._id = info._id
      infoData.name = info.name
      infoData.isAward = true
      // 中奖了给奖品
      userAwared.hasAward = "in"
      userAwared.forAward = info._id
      userAwared.isGet = false
      // 更新奖品数量
      await setAward(info)
    }
    await setLog(userInfo, userAwared)
    return {
      success: true,
      data: infoData,
    }
 
}
module.exports = {
  info,
  buy
}